﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using SSRSViewer.Core;

namespace SSRSViewer.Win
{
    partial class MultipleValidValuesUserControl : UserControl, IMultipleValidValuesUserControl
    {
        public MultipleValidValuesUserControl()
        {
            InitializeComponent();
        }
        public RdlDataProvider DataProvider { get; set; }
        public SqlConnection Connection { get; set; }
        public RdlValidValuesParser ValuesParser { get; set; }

        public void Initialize()
        {
            if (DataProvider == null)
                throw new NullReferenceException("Dataprovider was not assigned.");
            if (Connection == null)
                throw new NullReferenceException("Sql Connection was not assigned.");

            SqlCommand cmd = new SqlCommand(DataProvider.CommandText, Connection);
            SqlDataReader reader;

            if (Connection.State != ConnectionState.Open)
                Connection.Open();

            reader = cmd.ExecuteReader();

            while (reader.Read())
                checkedListBox1.Items.Add(new CheckboxItem()
                {
                    Key = reader.GetValue(reader.GetOrdinal(ValuesParser.LabelField)).ToString(),
                    Value = reader.GetValue(reader.GetOrdinal(ValuesParser.ValueField))
                });
            Connection.Close();
        }

        #region IParameterEditor Members
        public object EditValue
        {
            get            
            {
                return checkedListBox1.CheckedItems.Cast<CheckboxItem>().Select(cb => cb.Value.ToString()).ToArray();
            }
            set
            {
                string[] strValues = Regex.Split(value.ToString(), ",");
                foreach (var check in this.checkedListBox1.Items.Cast<CheckboxItem>())
                {
                    if (strValues.Contains(check.Value.ToString()))
                        checkedListBox1.SetItemChecked(checkedListBox1.Items.IndexOf(check), true);
                }
            }
        }
        public string Prompt
        {
            get { return lbPrompt.Text; }
            set { lbPrompt.Text = value; }
        }
        public RdlReportParameter EditingParameter { get; set; }
        #endregion
    }
}
